package com.interfaces;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.common.web.CommonJspKeys;
import com.common.web.CommonKeys;
import com.common.web.Json;
import com.common.web.ReturnCodes;
import com.common.web.SelectJson;
import com.core.sendAgent.bo.SendAgentBo;
import com.core.sendAgent.dto.SendAgentSearchCondition;
import com.core.travelAgent.TravelAgentJspKeys;
import com.core.travelAgent.bo.TravelAgentBo;
import com.core.travelAgent.dto.TravelAgentSearchCondition;
import com.core.travelAgent.pojo.AgentRelation;
import com.core.user.bo.UserBo;
import com.core.user.pojo.User;
import com.google.gson.reflect.TypeToken;
import com.util.DataBaseUtil;
import com.util.GsonUtil;
import com.util.exception.ComRuntimeException;
import com.util.exception.ComSystemException;
import com.util.framework.BaseController;
@Controller
public class TravelAgentController extends BaseController{
	@Resource
	private TravelAgentBo travelAgentBo;
	@Resource
	private UserBo userBo;
	@Resource
	private  SendAgentBo sendAgentBo;
	
	protected Logger log = Logger.getLogger(TravelAgentController.class);
 	public static final String URL_ENTITY = "/travelAgent";
    public static final String URL_GOTO_MAIN_PAGE = URL_ENTITY + "/goto_main_page";
    public static final String URL_GOTO_ADD_UPDATE_PAGE = URL_ENTITY + "/goto_add_update_page";
    public static final String URL_GOTO_ADD_PAGE = URL_ENTITY + "/goto_add_page";
    public static final String URL_GOTO_UPDATE_PAGE = URL_ENTITY + "/goto_update_page";
    public static final String URL_ADD = URL_ENTITY + "/add";
    public static final String URL_UPDATE = URL_ENTITY + "/update";
    public static final String URL_DELETE = URL_ENTITY + "/delete";
    public static final String URL_DB_SEARCH = URL_ENTITY+"/search";
    public static final String URL_SEARCH = URL_ENTITY+"/search1";
    public static final String URL_INTERVAL= URL_ENTITY+"/interval";
    public static final String URL_ADDRELATION = URL_ENTITY+"/addRelation";
    public static final String URL_UPDATERELATION = URL_ENTITY+"/updateRelation";
    public static final String URL_DELRELATION = URL_ENTITY+"/delRelation";
    public static final String URL_SHOWRELATION = URL_ENTITY+"/showRelation";
    public static final String URL_SEARCHSENDAGENT = URL_ENTITY+"/searchSendAgent";
    public static final String URL_NAME = URL_ENTITY+"/getName";
    @RequestMapping(value=URL_DB_SEARCH,method=RequestMethod.POST,produces={"application/json;charset=utf-8"})
	@ResponseBody
	public String searchData( TravelAgentSearchCondition sc,HttpSession session){
		String msg="";
		List<TravelAgentSearchCondition>data = travelAgentBo.getAgentSearchConditions(sc);
		DataBaseUtil<TravelAgentSearchCondition> db = new DataBaseUtil<TravelAgentSearchCondition>();
		int totalCount=travelAgentBo.getAllRecodeCnt(sc);
		if(data.size()==0){
			msg="{\"draw\":"+sc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
		}else{
			db.setTotalCount(totalCount);
			db.setRecordsFiltered(totalCount);
			db.setData(data);
			db.setDraw(sc.getDraw());
			msg = GsonUtil.gson.toJson(db);
		}
		return msg;
	}
	@RequestMapping(value=URL_GOTO_MAIN_PAGE,method=RequestMethod.GET)
	public ModelAndView gotoMainPage(HttpSession session,TravelAgentSearchCondition sc) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		ModelAndView modelAndView= new ModelAndView("/travelAgent/travelAgent_main");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo,userInfo);
		return modelAndView;
	}

	@RequestMapping(value=URL_GOTO_ADD_UPDATE_PAGE,method=RequestMethod.GET)	
	public ModelAndView URL_GOTO_ADD_UPDATE_PAGE(HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		ModelAndView modelAndView = new ModelAndView("travelAgent/travelAgent_add");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		return modelAndView;
	}
	
	@RequestMapping(value = URL_GOTO_UPDATE_PAGE, method = RequestMethod.GET)
	public ModelAndView URL_GOTO_UPDATE_PAGE(TravelAgentSearchCondition sc,HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		TravelAgentSearchCondition sc1 = travelAgentBo.getById(sc);
		ModelAndView modelAndView = new ModelAndView("travelAgent/travelAgent_update");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		modelAndView.addObject(TravelAgentJspKeys.JspParam_TravelAgent, sc1);
		return modelAndView;
	}
	
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = URL_ADD, method = RequestMethod.POST)
	public Json add(TravelAgentSearchCondition sc, HttpSession session) {
		Json json = new Json();
		if(travelAgentBo.getById(sc)!=null){
			json.setReturnCode(103);
			json.setMsg("数据库已经拥有该对象，不能重复添加！");
			return json;
		}
		try {
			User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
			sc.setAddUserId(String.valueOf(userInfo.getId()));
			sc.setAddDate(new Date());
			travelAgentBo.add(sc);
			json.setSuccess(true);
			json.setReturnCode(0);
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
	@ResponseBody
	@RequestMapping(value = URL_NAME, method = RequestMethod.POST)
	public String getNameById(Long id){
		if(travelAgentBo.getNameById(id)==null){
			return " ";
		}
		return travelAgentBo.getNameById(id);
	}
//	添加旅行社送签社关系
	@ResponseBody
	@RequestMapping(value = URL_ADDRELATION, method = RequestMethod.POST)
	public Json addRelation(AgentRelation agentRelation, HttpSession session) {
		SendAgentSearchCondition sendAgent=sendAgentBo.getById2(agentRelation.getSendAgentId());
		agentRelation.setSendAgentCode(sendAgent.getCode());
		agentRelation.setSendAgentName(sendAgent.getSendAgentName());
		Json json = new Json();
		try {
			travelAgentBo.addRelation(agentRelation);
			json.setSuccess(true);
			json.setReturnCode(0);
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
//	更新旅行社送签社关系
	@ResponseBody
	@RequestMapping(value = URL_UPDATERELATION, method = RequestMethod.POST)
	public Json updateRelation(AgentRelation agentRelation, HttpSession session) {
		SendAgentSearchCondition sendAgent=sendAgentBo.getById2(agentRelation.getSendAgentId());
		agentRelation.setSendAgentCode(sendAgent.getCode());
		agentRelation.setSendAgentName(sendAgent.getSendAgentName());
		Json json = new Json();
		try {
			AgentRelation tempRelation=travelAgentBo.getRelationById(agentRelation.getId());
			if (tempRelation!=null) {
				travelAgentBo.updateRelation(agentRelation);
				json.setSuccess(true);
				json.setReturnCode(0);
			}
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
//	删除关系
	@RequestMapping(value = URL_DELRELATION, method = RequestMethod.POST)
	@ResponseBody
	public Json delRelation(AgentRelation agentRelation, HttpSession session) {
		Json json = new Json();
		try {
			travelAgentBo.delRelation(agentRelation);
			json.setSuccess(true);
			json.setReturnCode(0);
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
//	获取并展示关系
	@RequestMapping(value = URL_SHOWRELATION,method=RequestMethod.POST,produces={"application/json;charset=utf-8"})
	@ResponseBody
	public String showRelation(AgentRelation agentRelation, HttpSession session) {
		String msg="";
		List<AgentRelation>rows = travelAgentBo.getInterval(agentRelation);
		DataBaseUtil<AgentRelation> db = new DataBaseUtil<AgentRelation>();
		int totalCount = travelAgentBo.searchRelationCnt(agentRelation);
		if (rows.size()==0) {
			msg="{\"total\":0,\"recordsFiltered\":0,\"rows\": []}";
		}else{
			db.setRows(rows);
			db.setTotal(totalCount);
			msg = GsonUtil.gson.toJson(db);
		}
		return msg;
	}
	
	@ResponseBody
	@RequestMapping(value = URL_UPDATE, method = RequestMethod.POST)
	public Json update(TravelAgentSearchCondition sc, HttpSession session) {
		Json json = new Json();
		try {
			User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
			sc.setAddUserId(String.valueOf(userInfo.getId()));
			sc.setAddDate(new Date());
			travelAgentBo.update(sc);
			json.setSuccess(true);
			json.setReturnCode(0);
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
	
	@ResponseBody
	@RequestMapping(value = URL_DELETE, method = RequestMethod.POST)
	public Json delete(HttpServletRequest request) {
		String items = request.getParameter("delitems");
	    String[] strs = items.split(",");
		Json json = new Json();
		for (int i = 0; i < strs.length; i++) {  
			try {
				travelAgentBo.del(strs[i]);
				json.setSuccess(true);
			} catch (ComRuntimeException e) {
				json = new Json(e.getErrorCode(), e.getMessage());
			} catch (ComSystemException e) {
				log.error("error", e);
				json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
			} catch (Throwable e) {
				log.error("error", e);
				json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
						+ e.getMessage());
			}
		}
		return json;
	}
//	别的地方获取旅行社
	@ResponseBody
    @RequestMapping(value = URL_SEARCH, method = RequestMethod.POST,produces={"application/json;charset=utf-8"})
    public String searchCustodianBank(TravelAgentSearchCondition sc) {
        String msg="";
        try {
        	List<SelectJson> sendLists= travelAgentBo.searchDtoList(sc);
            Integer totalRecordCount = travelAgentBo.getAllRecodeCnt(sc);
            msg=GsonUtil.gson.toJson(sendLists,new TypeToken<List<SelectJson>>(){}.getType());
            msg="{\"total_count\": "+totalRecordCount+",\"items\":"+ msg+"}";
        } catch (Exception e) {
        	log.error("error", e);
        	msg="{\"total_count\": "+0+",\"items\":[]}";
        }
       return msg;
	}
//	别的地方获取该旅行社所关联的送签社
	@ResponseBody
    @RequestMapping(value = URL_SEARCHSENDAGENT, method = RequestMethod.POST,produces={"application/json;charset=utf-8"})
	public String searchSendAgent(SendAgentSearchCondition sc,HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		User userInfo2 =userBo.getById(userInfo);
		AgentRelation tempRelation = new AgentRelation();
		tempRelation.setTravelAgentId(userInfo2.getTravelAgentId());
		tempRelation.setSendAgentCode(sc.getCode());
		String msg="";
        try {
        	List<SelectJson> sendLists= travelAgentBo.getUserSendAgent(tempRelation);
            Integer totalRecordCount = travelAgentBo.getUserSendAgentCnt(tempRelation);
            msg=GsonUtil.gson.toJson(sendLists,new TypeToken<List<SelectJson>>(){}.getType());
            msg="{\"total_count\": "+totalRecordCount+",\"items\":"+ msg+"}";
        } catch (Exception e) {
        	log.error("error", e);
        	msg="{\"total_count\": "+0+",\"items\":[]}";
        }
       return msg;
	}
	
}
